package cn.claim.storage.tools;

import com.google.gson.Gson;

import java.io.Reader;

/**
 * Created by claim on 17-7-9.
 */
public interface JSONParsable {
    Gson gson = new Gson();

    default String toJSON() {
        return gson.toJson(this);
    }

    /**
     * parse JSON String to a JSONParsable Object
     *
     * @param type must be a Class implemented JSONParsable interface, if not, a IllegalArgumentException will be threw.
     */
    static <T> T parse(String JSON, Class<T> type) {
        if (!(JSONParsable.class.isAssignableFrom(type)
                || type == int.class || type == long.class || type == byte.class || type == boolean.class || type == String.class
                || type == short.class || type == float.class || type == double.class))
            throw new IllegalArgumentException("Type should be a Class implemented JSONParsable interface");
        return gson.fromJson(JSON, type);
    }

    /**
     * parse JSON stream to a JSONParsable Object
     * Used on a Reader only contains a JSON Object.
     *
     * @param type must be a Class implemented JSONParsable interface, if not, a IllegalArgumentException will be threw.
     */
    static <T> T parse(Reader JSON, Class<T> type) {
        if (!(JSONParsable.class.isAssignableFrom(type)
                || type == int.class || type == long.class || type == byte.class || type == boolean.class || type == String.class
                || type == short.class || type == float.class || type == double.class))
            throw new IllegalArgumentException("Type should be a Class implemented JSONParsable interface");
        return gson.fromJson(JSON, type);
    }
}
